package it.davial.mgwt.server;

import static it.softphone.commons.util.LogUtil.logger; 
import static it.davial.mgwt.server.Utility.ManagmentId;
import static  it.davial.mgwt.server.Sql.Photo.*;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;



import it.davial.mgwt.client.Photo;


public class PhotoUtils {

	
	/**
	 * find all photo without criteria
	 * @return List<Photo>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Photo> findAllPhoto()throws Exception{
		
		EntityManager newEm=null;
		List<Photo> result=new ArrayList<Photo>();
		Utility.Logs.startFunction("PhotoUtils", "findAllPhoto", new String[]{});
		
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			
			logger.info(" Photo(s) found:".concat(String.valueOf(result.size()))  );
			
			result =(List<Photo>)newEm.createNativeQuery(SELECT_ALL,Photo.class).getResultList();
	
			logger.info(" Photo(s) found:".concat(String.valueOf(result.size()))  );
			
		}catch(javax.persistence.NoResultException e){
			logger.warn("PhotoUtils:findAllPhoto",e);
		}catch(Exception e){
			logger.error("PhotoUtils:findAllPhoto",e);
			throw e;
		}finally{
			newEm.close();
		}
		return result;
	}
	
	/**
	 * find all photo without criteria
	 * @return List<Photo>
	 * @throws Exception
	 */
	public static Photo findPhotoById(int id)throws Exception{
		
		EntityManager newEm=null;
		Photo result=null;
		Utility.Logs.startFunction("PhotoUtils", "findPhotoById", new String[]{String.valueOf(id)});
		
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			
			
			result =(Photo)newEm.createNativeQuery(SELECT_BY_ID,Photo.class).
										setParameter(1,id ).getSingleResult();
	
			logger.info(" Photo found:".concat(String.valueOf(result))  );
			
		}catch(javax.persistence.NoResultException e){
			logger.warn("PhotoUtils:findPhotoById",e);
		}catch(Exception e){
			logger.error("PhotoUtils:findPhotoById",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return result;
	}

	
	/**
	 * find all photo without criteria
	 * @return List<Photo>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Photo> findPhotoByIdPatientAndDate(int idPatient,String date)throws Exception{
		
		EntityManager newEm=null;
		List<Photo> result=null;
		Utility.Logs.startFunction("PhotoUtils", "findPhotoByIdPatientAndDate", new String[]{String.valueOf(idPatient),date});
		
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			
			
			result =(List<Photo>)newEm.createNativeQuery(SELECT_BY_IDPERSON_DATE,Photo.class).
										setParameter(1,idPatient ).
										setParameter(2,idPatient ).
										setParameter(3,date ).
										setParameter(4,date ).
										getResultList();
	
			logger.info(" Photo found:".concat(String.valueOf(result))  );
			
		}catch(javax.persistence.NoResultException e){
			logger.warn("PhotoUtils:ffindPhotoByIdPatientAndDate",e);
		}catch(Exception e){
			logger.error("PhotoUtils:ffindPhotoByIdPatientAndDate",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return result;
	}
	
	/**
	 * create a photo
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean createPhoto(Photo photo)throws Exception{
		EntityManager newEm=null;
		EntityTransaction tx =null;
		Utility.Logs.startFunction("PhotoUtils", "createPatient", new String[]{photo.toString()});
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			tx = newEm.getTransaction();
		    tx.begin();
		    photo.setIdPhoto(ManagmentId.getNextId(IdEntity.PHOTO));
		    photo.setDataInsert(Utility.Date.nowDateDb());
		    photo.setDataUpdate(Utility.Date.nowDateDb());
			newEm.persist(photo);
			logger.info("photo created..." );
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			logger.error("PhotoUtils:createPhoto",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return true;
	}
	
	/**
	 * merge a photo
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean mergePhoto(Photo photo)throws Exception{
		EntityManager newEm=null;
		EntityTransaction tx =null;
		Utility.Logs.startFunction("PhotoUtils", "merge", new String[]{photo.toString()});
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			tx = newEm.getTransaction();
		    tx.begin();
		    photo.setDataUpdate(Utility.Date.nowDateDb());
		    photo.setDataInsert(Utility.Date.webFormatToDateDb(photo.getDataInsert()));

			newEm.merge(photo);
			logger.info("photo mergeed..." );
			 tx.commit();
		}catch(Exception e){
			tx.rollback();
			logger.error("PhotoUtils:mergePhoto",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return true;
	}
	
	/**
	 * delete a patient
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean deletePhoto(Photo photo)throws Exception{
		EntityManager newEm=null;
		EntityTransaction tx =null;
		Utility.Logs.startFunction("PhotoUtils", "delete", new String[]{photo.toString()});
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			tx = newEm.getTransaction();
		    tx.begin();
		    photo.setState(Utility.Costants.DISABLED);
			logger.info(String.format("photo delete...[%s]",photo) );
			photo.setDataUpdate(Utility.Date.nowDateDb());
		    photo.setDataInsert(Utility.Date.webFormatToDateDb(photo.getDataInsert()));

			newEm.merge(photo);
			
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			logger.error("PhotoUtils:deletePhoto",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return true;
	}
	
	
}
